//
//  MainViewController.swift
//  Weibo
//
//  Created by apple on 15/6/24.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let tb = MainTabBar()
///  用kvc替换掉系统自带的tabbar
        setValue(tb, forKeyPath: "tabBar")
///   添加所有的控制器
        addChildViewControllers()
        tb.compoesButton.addTarget(self, action: "compoesButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
    }
    ///中间按钮点击事件
    func compoesButtonClick(){
    
        let nvc = UINavigationController(rootViewController: ComposeViewController())
        presentViewController(nvc, animated: true, completion: nil)
    
    }
///  添加所有的控制器
    func addChildViewControllers() {
        //加载json 动态加载控制器
        let path = NSBundle.mainBundle().pathForResource("vcs.json", ofType: nil)
        let data = NSData(contentsOfFile:path!)
        //处理异常 do catch
        do{
        
//这里如果能确保成功  可以强行try 程序崩溃了自己负责
            let array = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
            for dict in array as![[String:String]]{
            addChildViewController(dict["vcName"]!, title: dict["title"]!, imageName: dict["imageName"]!)
            
            }
        
        }catch{
        print(error)
        
        addChildViewController("HomeTableViewController", title: "首页", imageName: "tabbar_home")
        addChildViewController("MessageTableViewController", title: "消息", imageName: "tabbar_message_center")
        addChildViewController("DiscoverTableViewController", title: "发现", imageName: "tabbar_discover")
        addChildViewController("ProfileTableViewController", title: "我", imageName: "tabbar_profile")
        
        }

        
    }
///  添加一个控制器
    func addChildViewController(vcName: String, title: String, imageName: String) {
        
        let ns = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String
        let cls:AnyClass = NSClassFromString(ns + "." + vcName)!
        
        let vc = cls.new() as! UIViewController
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        vc.tabBarItem.selectedImage = UIImage(named: imageName + "_highlighted")
        
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
    }

}
